Implement instrumentation.js by creating a file in your project root that exports a register function, called once when the Next.js server starts
The instrumentation.js file in Next.js is a special file used to integrate monitoring, logging, and observability tools into your application. It runs server-side code when your Next.js server instance initializes, making it ideal for setting up OpenTelemetry, error tracking, or any initialization logic that should execute once at startup. Starting with Next.js 15, this feature is stable and includes additional error tracking capabilities through the onRequestError function.
Create the instrumentation file: Place instrumentation.js|ts in your project's root directory (or inside src folder if using one) - not inside app or pages directories
Export a register function: This function is called once when the Next.js server instance is initiated and can be async
For Next.js 14 or earlier: Enable experimental flag in next.config.js with experimental.instrumentationHook = true
Use environment-specific code: Check process.env.NEXT_RUNTIME to conditionally import code for Node.js vs Edge runtime
Import side-effect modules: Use await import() inside the register function for packages with side effects rather than importing at the top of the file
For production use, a common implementation pattern is integrating OpenTelemetry for observability. The @vercel/otel package provides a streamlined way to add OpenTelemetry instrumentation to your Next.js application. You can also create custom instrumentation for browser-side monitoring by conditionally initializing telemetry in your app component when running on the client side.